package com.smartphonedev.service;

import java.util.Calendar;

import com.smartphonedev.function.SmsFunc;
import com.smartphonedev.variables.Constants;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;

/**
 * This is an example of implementing an application service that will run in
 * response to an alarm, allowing us to move long duration work out of an
 * intent receiver.
 * 
 * @see AlarmService
 * @see AlarmService_Alarm
 */
public class AlarmService extends Service {
	@Override
	public void onCreate() {
		SharedPreferences sp = this.getSharedPreferences(Constants.foldername, 0);
		String getnumber = sp.getString(Constants.tab2number, "");
		String gethour = sp.getString(Constants.tab2spinner, "");
		int converthour = Integer.parseInt(gethour);
		Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR_OF_DAY); 
		String lat = Double.toString(Constants.currentlatitude);
		String lon = Double.toString(Constants.currentlongitude);
		String getname = sp.getString(Constants.saveusername, "");
		if(hour == converthour){
			SmsFunc.sendASms(this, getnumber, "sendcode:" + lat + ":" + lon + ":" + getname);
		}
		Thread thr = new Thread(null, mTask, "AlarmService_Service");
		thr.start();
	}
	/**
	 * The function that runs in our worker thread
	 */
	Runnable mTask = new Runnable() {
		public void run() {
			long endTime = System.currentTimeMillis() + 15*1000;
			while (System.currentTimeMillis() < endTime) {
				synchronized (mBinder) {
					try {
						mBinder.wait(endTime - System.currentTimeMillis());
					} catch (Exception e) {
					}
				}
			}

			// Done with our work...  stop the service!
			AlarmService.this.stopSelf();
		}
	};
	@Override
	public void onDestroy() {

	}

	/**
	 * The function that runs in our worker thread
	 */

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}


	/**
	 * This is the object that receives interactions from clients.  See RemoteService
	 * for a more complete example.
	 */
	private final IBinder mBinder = new Binder() {
		@Override
		protected boolean onTransact(int code, Parcel data, Parcel reply,
				int flags) throws RemoteException {
			return super.onTransact(code, data, reply, flags);
		}
	};
}

